/**
 *
 * Copyright 2016-present scrm
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
import React from 'react';
import {
  InteractionManager,
  ListView,
  View,
  StyleSheet
} from 'react-native';

import MemberList from './MemberList';
import LoadingView from '../../components/LoadingView';
import EmptyView from './EmptyView';
import { 
  getDataList, 
  modifyList, 
  mergeArrayOfObject, 
  diffArrayOfObject, 
  removeUncheckedItem 
} from '../../utils/ItemsUtil';
import MemberCell from './MemberCell';
import store from 'react-native-simple-store';
import * as types from '../../constants/ActionTypes';
import LoadingSpinnerOverlay from '../../components/LoadingSpinnerOverlay';
import ToastUtil from '../../utils/ToastUtil';

class MemberChose extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      memberList: []
    };
    this.renderMemberCell = this.renderMemberCell.bind(this);
    this.onItemChecked = this.onItemChecked.bind(this);
    this.onSaveSelected = this.onSaveSelected.bind(this);
    this.isGoBack = false;
    this.mounted = false;
  }

  componentDidMount () {
    const { memberActions, member } = this.props;
    this.props.navigation.setParams({ handleCheck: this.onSaveSelected });

    InteractionManager.runAfterInteractions(async () => {
      this.mounted = true;
      if (!member.MemberList) {
        const token = await store.get('token')
        const siteId = await store.get('site_id')
        memberActions.requestAllMemberList(token, siteId, 'teams', true)
      }
    });
  }

  componentWillUnmount () {
    this.mounted = false;
    this.isGoBack = true;
  }

  componentWillReceiveProps(nextProps) {
    const { member, team } = nextProps;
    if (this.mounted && member.loading === false  
      && this.state.memberList !== member.memberList) {
        const merged = this.mergeSelectedMembers(member.memberList);
        // console.log('mergeSelectedMembers', member.memberList, merged);
        this.setState({memberList: merged})
    }
    
    if(team.type === types.START_SAVE_TEAM) {
      this._modalLoadingSpinnerOverLay.show()
    } else if(this.isGoBack === true && team.type === types.RESPONSE_SAVE_TEAM) {
      const { goBack } = this.props.navigation;
      const { teamActions } = this.props;
      this._modalLoadingSpinnerOverLay.hide();
      requestAnimationFrame(() => goBack())
    }  
  }

  mergeSelectedMembers (memberList) {
    const { team, isManager } = this.props.navigation.state.params;
    let members = (team.team_managers || []).concat(team.team_members || []);
    if (isManager) {
      members = (team.team_managers || []).concat(modifyList(
          team.team_members, 
          undefined, 
          'disabled', 
          true, 
          null
        ));
    } else {
      members = (team.team_members || []).concat(modifyList(
        team.team_managers, 
        undefined, 
        'disabled', 
        true, 
        null
      ));
    }
    members = modifyList(members, undefined, 'checked', true, null);
    return mergeArrayOfObject(memberList, members, 'suid')
  }

  onItemChecked (item) {
    const { isManager,team } = this.props.navigation.state.params
    let refreshMemberList = this.state.memberList;
    let members = removeUncheckedItem(this.state.memberList);
    members = diffArrayOfObject(members, team.team_members, 'suid');
    if (isManager && members.length === 1 && members[0].suid === item.suid) {
      ToastUtil.showShort('不能取消最后一个管理员!');
    } else {
      refreshMemberList = modifyList(
        getDataList(this.state.memberList), 
        ['suid', item.suid],  
        'checked', 
        !item.checked, 
        false, 
        true
      )
    }
    
    requestAnimationFrame(() => this.setState({memberList: refreshMemberList}))
  }

  renderMemberCell (section) {
    const { isManager } = this.props.navigation.state.params
    return (
      <MemberCell 
      checkbox={true}
      item={section.item}
      rightText={(section.item.disabled ? (isManager ? '成员' : '主管') : false)}
      checked={section.item.checked}
      onChecked={this.onItemChecked}
      />
    )
  }

  renderContent = (memberList) => {
    const { member } = this.props;
    const { team } = this.props.navigation.state.params;
    if (member.loading) return <LoadingView />;
    const isEmpty = memberList.length === 0;

    team.isRefreshing = member.loading;
    team.refreshing = member.loading;
    const evProps = Object.assign({}, team, member);
    // console.log('renderContent', team, member, evProps)
    if (isEmpty) {
      return <EmptyView team={team} {...evProps} />;
    }

    return (
      <MemberList
        cell={this.renderMemberCell}
        memberList = {memberList}
        renderHeaderContent = {this.renderManagerListView}
      />
    );
  }

  onSaveSelected () {
    const { isManager, team } = this.props.navigation.state.params
    let members = removeUncheckedItem(this.state.memberList); 
    if (isManager) {
      members = diffArrayOfObject(members, team.team_members, 'suid');
      team.team_managers = members
    } else {
      members = diffArrayOfObject(members, team.team_managers, 'suid');
      team.team_members = members
    }
    const { teamActions } = this.props;
    store.get('token').then(token => 
      store.get('site_id')
        .then(siteId => teamActions.requestSaveTeam(team, siteId, token))
    );

    this.isGoBack = true;
  };

  render () {
    const { member } = this.props;
    return (
      <View style={styles.containerStyle}>
        {
          this.renderContent(
            this.state.memberList
          )
        }
        <LoadingSpinnerOverlay
        ref={ component => this._modalLoadingSpinnerOverLay = component }/>
      </View>
    );
  }
}

MemberChose.propTypes = {

}

const styles = StyleSheet.create({
  containerStyle: {
    flex: 1
  }
})

export default MemberChose;
